 package com.meeruu.sg.account.core.web.config;

 import com.alibaba.druid.pool.DruidDataSource;
 import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
 import org.apache.ibatis.session.SqlSessionFactory;
 import org.mybatis.spring.SqlSessionFactoryBean;
 import org.mybatis.spring.SqlSessionTemplate;
 import org.mybatis.spring.annotation.MapperScan;
 import org.springframework.context.annotation.Bean;
 import org.springframework.context.annotation.Configuration;
 import org.springframework.context.annotation.Primary;
 import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
 import org.springframework.jdbc.datasource.DataSourceTransactionManager;

 @Configuration
 @MapperScan(value = "com.meeruu.sg.account.core.domain.mapper", sqlSessionTemplateRef = "sqlSessionTemplate")
 public class DBConfiguration {

     @Bean
     @Primary
     public DruidDataSource druidDataSource() {
         return DruidDataSourceBuilder.create().build();
     }

     @Primary
     @Bean(name = "sqlSessionFactory")
     public SqlSessionFactory initSqlSessionFactory() throws Exception {
         SqlSessionFactoryBean factoryBean = new SqlSessionFactoryBean();
         factoryBean.setDataSource(druidDataSource());
         PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
         factoryBean.setMapperLocations(resolver
                 .getResources("classpath:mapper/*.xml"));
         factoryBean.setTypeAliasesPackage("com.meeruu.sg.account.core.domain.model");
         factoryBean.setConfiguration(mybatisConf());

         return factoryBean.getObject();
     }

     @Bean(name = "mybatisConf")
     public org.apache.ibatis.session.Configuration mybatisConf() {
         org.apache.ibatis.session.Configuration configuration = new org.apache.ibatis.session.Configuration();
         configuration.setUseGeneratedKeys(true);
         return configuration;
     }

     @Primary
     @Bean(name = "dataSourceTransactionManager")
     public DataSourceTransactionManager initDataSourceTransactionManager() {
         return new DataSourceTransactionManager(druidDataSource());
     }

     @Primary
     @Bean(name = "sqlSessionTemplate")
     public SqlSessionTemplate initSqlSessionTemplate() throws Exception {
         return new SqlSessionTemplate(initSqlSessionFactory());
     }
 }
